package com.example.memo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.memo.Bean.noteBean;
import com.example.memo.db.MysqlOpenHelper;

import java.text.SimpleDateFormat;
import java.util.Date;


public class addNoteFragment extends AppCompatActivity implements  View.OnClickListener {

    private ImageView back_btn;

    private ImageView qx;

    private ImageView wc;

    private TextView shijian ;
    private EditText biaoti;
    private EditText neirong;

    private SQLiteDatabase sqLiteDatabase;
    private Spinner spinner;
    private String id;

    private String str1;
    private String str2;
    private  String text;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_add_note);

         initView();
         initData();
        //接收id
        Intent intent=getIntent();
        id = intent.getStringExtra("id");
        if(id !=null){
            getData();
        }
       //分类标签
        editsort();
        //从页面加载开始保存字符串用于判断是修改还是添加
         str1 = biaoti.getText().toString();
         str2 = neirong.getText().toString();
    }

    void initView(){
        back_btn = findViewById(R.id.fh);
        qx = findViewById(R.id.cx);
        wc = findViewById(R.id.wc);
        shijian=findViewById(R.id.createdate);
        biaoti=findViewById(R.id.title_note);
        neirong=findViewById(R.id.content_note);
        back_btn.setOnClickListener(this);
        qx.setOnClickListener(this);
        wc.setOnClickListener(this);
        spinner=findViewById(R.id.sort);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.fh:
                backTo();
                break;
            case R.id.cx:
                Toast.makeText(this, "抱歉目前没有该功能", Toast.LENGTH_SHORT).show();
                break;
            case R.id.wc:
                   inset_Add();
                break;
        }

    }

    public void initData(){
        //插入数据时注意，一定要传入最新的数据库版本号
        MysqlOpenHelper mysqlOpenHelper=new MysqlOpenHelper(this);
        sqLiteDatabase=mysqlOpenHelper.getWritableDatabase();
    }
     // 修改分类标签
    public void editsort(){
        //定义分类
        String[] items=getResources().getStringArray(R.array.sort);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_list_drop2, items);
        //第一个参数表示在哪个Activity上显示，第二个参数是系统下拉框的样式，第三个参数是数组。
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                if(position!=0){
                    Log.e("log","我选择了它"+position);
                    text = spinner.getItemAtPosition(position).toString();
                    if(position==3){
                    showEditDialog(items,adapter);

                    //实现自定义分类
                }
                }



            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }
    void backTo(){
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
    }
    //点击完成
    void inset_Add(){
        //isEmpty() 方法返回一个 boolean 值，用于判断字符串是否为空
        System.out.println(str1.isEmpty());
        System.out.println(str2.isEmpty());
        System.out.println(text);
        if((!str1.isEmpty()&&str2.isEmpty())||(str1.isEmpty()&&!str2.isEmpty())||(!str1.isEmpty()&&!str2.isEmpty())){
                //修改内容操操创建ContentValues对象
                str1 = biaoti.getText().toString();
                str2 = neirong.getText().toString();
                ContentValues values= new ContentValues();
                //插入对应的值会String.valueOf返回当前时间的字符串形式
                values.put("bt",str1);
                values.put("neirong",str2);
                values.put("fenglei",text);
                values.put("update_time", String.valueOf(new Date()));
                sqLiteDatabase.update("note_table",values,"id=?",new String[]{id});
                Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show();
                System.out.println("执行修改");
            }
            else {
                str1 = biaoti.getText().toString();
                str2 = neirong.getText().toString();
                //创建ContentValues对象
                ContentValues values= new ContentValues();
                //插入对应的值会String.valueOf返回当前时间的字符串形式
                values.put("bt",str1);
                values.put("neirong",str2);
                values.put("fenglei",text);
                values.put("create_time", String.valueOf(new Date()));
                sqLiteDatabase.insert("note_table",null,values);
                Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show();
                System.out.println("执行添加");
            }
        //执行返回
        backTo();

    }
    //获取数据
    public void getData() {
        String[] ziduan = {"bt","neirong","create_time","img","id","fenglei","update_time"};
        Cursor cursor=sqLiteDatabase.query("note_table",ziduan,"id=?",new String[]{id}
                ,null,null,null,"1");
        //判空
        if (cursor.getCount()>0){
            int value1=cursor.getColumnIndex("neirong");
            int value2=cursor.getColumnIndex("create_time");
            int value3=cursor.getColumnIndex("img");
            int value4=cursor.getColumnIndex("bt");
            int value5=cursor.getColumnIndex("id");
            int value6=cursor.getColumnIndex("fenglei");
            int value7=cursor.getColumnIndex("update_time");
                cursor.moveToFirst();
                String   nr = cursor.getString(value1);
                String   time = cursor.getString(value2);
                String   img = cursor.getString(value3);
                String   bt = cursor.getString(value4);
                String   id=cursor.getString(value5);
                String   fenglei = cursor.getString(value6);
                String   utime = cursor.getString(value7);
                //把日期转为相应的格式
                SimpleDateFormat dateFormat = new SimpleDateFormat("MM月dd日 HH:mm");
                String format = dateFormat.format(new Date(time));
                //  String format2 = dateFormat.format(new Date(utime));
                biaoti.setText(bt);
                neirong.setText(nr);
                shijian.setText(format);
        }else {
            Toast.makeText(this, "note获取信息失败", Toast.LENGTH_SHORT).show();
        }
        cursor.close();
    }

    private void showEditDialog(String[] items, ArrayAdapter<String> adapter) {
        AlertDialog.Builder builder = new AlertDialog.Builder(addNoteFragment.this);
        builder.setTitle("修改 Spinner 选项");

        // 创建并设置AlertDialog的视图
        View view = LayoutInflater.from(addNoteFragment.this).inflate(R.layout.simple_list_item, null);
     EditText  editText = view.findViewById(R.id.edit_type2);
        editText.setText(items[3]);
        editText.requestFocus();

        // 显示软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

        builder.setView(view);
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 保存新值
                String newItem = editText.getText().toString();
                items[3]=newItem;
                text=items[3];
               adapter.notifyDataSetChanged();
            }
        });

        builder.show();
    }

}